#include "dir.h"

int handle_remove(session_t *session, MYSQL *mysql, int netfd, const char*fileName){
    char buf[1024] = {0};

    int parentID = -1;
    char lastToken[MAX_PATH_LEN] = {0};
    int ret = cut_path(session,mysql,fileName,&parentID,lastToken,buf,sizeof(buf));
    if(ret != 0){
        sendtlv(netfd, buf);
        return -1;
    }
    //检查一下文件存在与否
    char query[MAX_QUERY_LEN] = {0};
    sprintf(query,
            "select id from file where username = '%s' and parent_id = %d "
            "and filename = '%s' and filetype = 'f' and tomb = 0",
            session->username, parentID, lastToken);
    ret = mysql_query(mysql, query);
    MYSQL_QUERY_CHECK(ret, mysql);

    MYSQL_RES *table = mysql_store_result(mysql);
    MYSQL_STORE_RESULT_CHECK(table,mysql);

    if(mysql_num_rows(table) == 0){
        mysql_free_result(table);
        strncpy(buf, "文件不存在.", sizeof(buf)-1);
        sendtlv(netfd, buf);
        return -1;
    }
    mysql_free_result(table);

    //执行逻辑删除
    bzero(query,sizeof(query));
    sprintf(query,
            "update file set tomb = 1 where username = '%s' and parent_id = %d "
            "and filename = '%s' and filetype = 'f'",
            session->username,parentID,lastToken);
    ret = mysql_query(mysql, query);
    MYSQL_QUERY_CHECK(ret, mysql);
    
    strncpy(buf, "删除成功.", sizeof(buf)-1);
    sendtlv(netfd, buf);
    return 0;
}
